const router = require('koa-router')()
const sequelize = require('../../dbHelper/db')
const { sys_dept: DeptModel } = require('../../dbHelper/db').models
const { Op } = require('sequelize')
const { hasParamsFiled, toTreeByRecursion } = require('../../utils')

router.prefix('/dept')

router.get('/getDeptList', async(ctx) => {
  const query = ctx.request.query

  const where = { del_flag: 0 }

  if (hasParamsFiled(query.dept_name)) {
    where.dept_name = {
      [Op.substring]: query.dept_name
    }
  }

  if (hasParamsFiled(query.status)) {
    where.status = query.status
  }

  const deptList = await DeptModel.findAll({
    where
  })

  ctx.body = {
    code: 0,
    data: deptList,
    msg: 'ok'
  }
})

router.get('/getTreeDept', async(ctx) => {
  const deptList = await DeptModel.findAll({
    where: {
      status: 0,
      del_flag: 0
    }
  })

  const parentIdNoneValue = 0

  const treeList = toTreeByRecursion(deptList, 'dept_id', 'parent_id', parentIdNoneValue, 'children')

  ctx.body = {
    code: 0,
    data: treeList,
    msg: 'ok'
  }
})

router.post('/addDept', async(ctx) => {
  // 请求参数校验
  ctx.verifyParams({
    parent_id: { type: 'number', required: true },
    dept_name: { type: 'string', required: true },
    order_num: { type: 'number', required: true },
    status: { type: 'enum', values: [0, 1] }
  })

  const params = ctx.request.body

  let objPost = await DeptModel.findOne({
    where: {
      dept_name: params.dept_name
    }
  })

  if (objPost) {
    ctx.body = {
      code: -1,
      msg: '部门名重复，创建失败！'
    }
  } else {
    objPost = await DeptModel.create({
      parent_id: params.parent_id,
      dept_name: params.dept_name,
      order_num: params.order_num,
      status: params.status,
      leader: params.leader || '',
      phone: params.phone || '',
      email: params.email || ''
    })

    ctx.body = {
      code: 0,
      msg: '创建成功！',
      data: objPost
    }
  }
})

router.put('/modifyDept', async(ctx) => {
  // 请求参数校验
  ctx.verifyParams({
    dept_id: { type: 'number', required: true },
    parent_id: { type: 'number', required: true },
    dept_name: { type: 'string', required: true },
    order_num: { type: 'number', required: true },
    status: { type: 'enum', values: [0, 1] }
  })

  const params = ctx.request.body

  const otherDept = await DeptModel.findOne({
    where: {
      dept_id: {
        [Op.ne]: params.dept_id
      },
      [Op.or]: {
        dept_name: params.dept_name
      }
    }
  })

  if (otherDept) {
    ctx.body = {
      code: -1,
      msg: '部门名重复，不能修改！'
    }
  } else {
    const t = await sequelize.transaction()

    try {
      await DeptModel.update({
        parent_id: params.parent_id,
        dept_name: params.dept_name,
        order_num: params.order_num,
        status: params.status,
        leader: params.leader,
        phone: params.phone,
        email: params.email
      }, {
        where: {
          dept_id: params.dept_id
        },
        transaction: t
      })

      let [sub_dept_ids] = await sequelize.query(`
      select dept_id from (
        select t1.dept_id,
        if(find_in_set(parent_id, @pids) > 0, @pids \:= concat(@pids, ',', dept_id), 0) as ischild
        from (
         select dept_id,parent_id from sys_dept t order by parent_id, dept_id
        ) t1,
        (select @pids \:= :pid) t2
      ) t3 where ischild != 0`, {
        replacements: {
          pid: params.dept_id
        }
      })

      if (Array.isArray(sub_dept_ids) && sub_dept_ids.length > 0) {
        sub_dept_ids = sub_dept_ids.map(dept => dept.dept_id)
        await DeptModel.update({
          status: params.status
        }, {
          where: {
            dept_id: {
              [Op.in]: sub_dept_ids
            }
          },
          transaction: t
        })
      }

      await t.commit()

      ctx.body = {
        code: 0,
        msg: '修改成功！'
      }
      return
    } catch (error) {
      t.rollback()
    }
  }
})

router.delete('/deleteDept', (ctx) => {
  const query = ctx.request.query

  if (query.dept_id === undefined) {
    ctx.body = {
      code: -1,
      msg: '参数错误'
    }
    return
  }

  DeptModel.update({
    del_flag: 2
  }, {
    where: {
      dept_id: query.dept_id
    }
  })

  ctx.body = {
    code: 0,
    msg: '删除成功！'
  }
})

module.exports = router
